package com.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Administrator
 *
 * @author jiangbang
 * @date 2016/8/31
 */
public class RefFiled {
    public double x;
    public Double y;

    public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException {
        Class c = RefFiled.class;
        Field xf = c.getField("x");
        Field yf = c.getField("y");

        RefFiled obj = new RefFiled();

        System.out.println(" 变更前 x=" + xf.get(obj));
        // 变更成员 x 值
        xf.set(obj, 1.1);
        System.out.println(" 变更后 x=" + xf.get(obj));

        System.out.println(" 变更前 y=" + yf.get(obj));
        // 变更成员 y 值
        yf.set(obj, 2.1);
        System.out.println(" 变更后 y=" + yf.get(obj));
    }

    private static Object check(Object obj,String flag) throws Exception
    {
        Class ts=obj.getClass();
        Field[] fs=ts.getDeclaredFields();
        Method[] ms=ts.getDeclaredMethods();
        StringBuffer fd=new StringBuffer();
        Map<String,Object> getMethodMap=new HashMap<String,Object>();
        Map<String,Method> setMethodMap=new HashMap<String,Method>();
        String methodName="";
        String value="";
        for(int i=0;i<fs.length;i++)
        {
            if(java.lang.String.class!=fs[i].getType())
            {
                fd.append(fs[i].getName());
            }
        }
        for(int i=0;i<ms.length;i++)
        {
            methodName=ms[i].getName().toLowerCase();
            if(methodName.indexOf("get")!=-1)
            {
                getMethodMap.put(methodName.substring(3), ms[i].invoke(obj, null));
            }
            else
            {
                setMethodMap.put(methodName.substring(3), ms[i]);
            }
        }
        Set keySet=getMethodMap.keySet();
        Iterator it=keySet.iterator();
        String key="";
        while(it.hasNext())
        {
            key=it.next().toString();
            if(fd.indexOf(key)==-1&&getMethodMap.get(key)!=null)
            {
                value=getMethodMap.get(key).toString().replaceAll(",", "").replaceAll(" ", "");
                if("".equals(value)||flag.equals(value))
                {
                    ((Method) setMethodMap.get(key)).invoke(obj, new Object[]{null});
                }
                else
                {
                    ((Method) setMethodMap.get(key)).invoke(obj, new Object[]{value});
                }
            }
        }
        return obj;
    }
}
